<template>
    <a-row v-if="formState.imageUrl" align="middle">
        <a-image style="width: 150px; max-height: 100%" :src="formState.imageUrl" alt="avatar" />
        <a-button style="margin-left: 10px" @click="formState.imageUrl = ''">更换头像</a-button>
    </a-row>
    <a-upload
        v-else
        v-model:file-list="fileList"
        list-type="picture-card"
        class="avatar-uploader"
        :show-upload-list="false"
        :before-upload="beforeUpload"
    >
        <div>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text" v-else>点击上传</div>
        </div>
    </a-upload>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, watch, toRefs } from 'vue'
import { uploadImg } from '@/views/homes/user-center/store'

export default defineComponent({
    name: 'UploadImg',
    props: {
        modelValue: {
            type: String,
            default: ''
        }
    },
    emits: ['update:modelValue'],
    setup(props, { emit }) {
        const state = reactive({
            loading: false,
            fileList: [],
            imageUrl: props.modelValue,
            formState: {} as any
        })
        watch(
            () => props.modelValue,
            (val) => {
                state.imageUrl = val
            }
        )
        watch(
            () => state.imageUrl,
            (val) => {
                emit('update:modelValue', val)
            }
        )
        const methods = {
            async beforeUpload(file: any) {
                state.loading = true
                const formdata = new FormData()
                formdata.append('image', file)
                try {
                    const res = await uploadImg(formdata)
                    state.formState.imageUrl = res.imageUrl
                } catch (err) {
                    console.log(err)
                } finally {
                    state.loading = false
                }
                return false
            }
        }
        return {
            ...toRefs(state),
            ...methods
        }
    }
})
</script>
